<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>画板</title>
</head>
<body>
    <canvas id="canvas">
        <script>
            let canvas = document.getElementById('canvas'); // DOM操作中按id获取元素的过程
            canvas.width = document.documentElement.clientWidth; // 指定元素的宽
            canvas.height = document.documentElement.clientHeight; // 指定元素的高

            let ctx = canvas.getContext('2d');

            let painting = false;
            let last = [];

            ctx.fillStyle = "black";
            ctx.strokeStyle = 'none';
            ctx.lineWidth = 5;
            ctx.lineJoin = 'miter';

            // 判断触屏设备。文档来源：https://cloud.tencent.com/developer/ask/49518
            var isTouchDevice = 'ontouchstart' in document.documentElement;

            function drawLine(x1, y1, x2, y2){
                 ctx.beginPath();
                 ctx.moveTo(x1, y1);
                 ctx.lineTo(x2, y2);
                 ctx.stroke();
            }

            // drawLine(0, 0, 500, 500);

            if (isTouchDevice) {
                canvas.ontouchstart = (e) =>{
                    last = [e.touches[0].clientX, e.touches[0].clientY];
                }
                canvas.ontouchmove = (e) =>{
                    let x = e.touches[0].clientX;
                    let y = e.touches[0].clientY;
                    drawLine(last[0], last[1], x, y);
                    last = [x, y];
                }
            }else{
                canvas.onmousedown = (e) =>{
                    painting = true;
                    last = [e.clientX, e.clientY];
                }

                canvas.onmousemove = (e) => {
                    if (painting === true){
                        drawLine(last[0], last[1], e.clientX, e.clientY);
                        last = [e.clientX, e.clientY];
                    }else{
                        console.log('Nothing to do');
                    }
                }

                canvas.onmouseup = () => {
                    painting = false;
                }
            }
        </script>
    </canvas>
</body>
</html>